//
//  QSAppTool.swift
//  TestSwift
//
//  Created by Song on 2018/5/7.
//  Copyright © 2018 Song. All rights reserved.
//

import UIKit

class QSAppTool: NSObject {
    /// 通过字符串创建class
    ///
    /// - Parameters:
    ///   - className: class名
    ///   - classType: class类型
    /// - Returns: class
    class func qs_createClass(_ className: String) -> AnyClass {
        // 获取命名空间
        guard let clasName = Bundle.main.infoDictionary!["CFBundleExecutable"] else {
            fatalError("命名空间不存在")
        }
        
        // 通过命名空间和类名转换成类
        guard let cls = NSClassFromString(clasName as! String + "." + className) else {
            fatalError("无法转换成相应类型")
        }
        
        return cls
    }
    
    /// 截屏，截取整个屏幕内容
    /// - Returns: 截图
    static func qs_screenShot() -> UIImage? {
        let imageSize = UIScreen.main.bounds.size
        
        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0.0)
        guard let context = UIGraphicsGetCurrentContext() else {
            UIGraphicsEndImageContext()
            return nil
        }
        
        for window in UIApplication.shared.windows {
            if window.responds(to: #selector(getter: window.screen)) || window.screen == UIScreen.main {
                context.saveGState()
                context.translateBy(x: window.center.x, y: window.center.y)
                context.concatenate(window.transform)
                context.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x, y: -window.bounds.size.height * window.layer.anchorPoint.y)
                window.layer.render(in: context)
                
                context.restoreGState()
            }
        }
        
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            UIGraphicsEndImageContext()
            return nil
        }
        UIGraphicsEndImageContext()
        return image
    }
    
    /// 截屏，根据给定的view
    /// - Parameter view: 给定的view
    /// - Returns: 截图
    class func qs_screenShot(_ view: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0)
        
        guard let context = UIGraphicsGetCurrentContext() else {
            UIGraphicsEndImageContext()
            return nil
        }
        view.layer.render(in: context)
        
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            UIGraphicsEndImageContext()
            return nil
        }
        UIGraphicsEndImageContext()
        return image
    }
    
    /// 异步获取图片尺寸
    ///
    /// - Parameter imgUrl: 图片url字符串
    class func qs_getImageSize(_ imgUrl: String, success: @escaping ((CGSize) -> ())) {
        DispatchQueue.global(qos: .default).async {
            var urlStr = imgUrl
            if imgUrl.hasPrefix("http://") || imgUrl.hasPrefix("https://") {
            } else {
                urlStr = Host + urlStr
            }
            
            if let url = URL.init(string: urlStr) {
                let data = try? Data.init(contentsOf: url)
                if data != nil {
                    if let image = UIImage.init(data: data!) {
                        success(image.size)
                        return
                    }
                }
            }
            
            success(CGSize.zero)
        }
    }
    
    /// 创建二维码
    ///
    /// - Parameters:
    ///   - content: 二维码内容
    ///   - width: 宽度
    ///   - iconImg: 中间的图片
    ///   - codeColor: 二维码颜色
    /// - Returns: 二维码图片
    class func qs_qrCode(content: String, width: CGFloat, iconImg: UIImage? = nil, codeColor: UIColor? = nil) -> UIImage? {
        // 给滤镜设置内容
        guard let data = content.data(using: .utf8) else {
            return nil
        }
        
        guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
        filter.setValue(data, forKey: "inputMessage")
        // 设置生成的二维码的容错率
        // value = @"L/M/Q/H"
        filter.setValue("H", forKey: "inputCorrectionLevel")
        
        // 获取生成的二维码
        guard let outPutImage = filter.outputImage else {
            return nil
        }
        // 设置二维码颜色
        let colorFilter = CIFilter.init(name: "CIFalseColor", parameters: ["inputImage":outPutImage,
                                                                           "inputColor0":CIColor(cgColor: codeColor?.cgColor ?? UIColor.black.cgColor),
                                                                           "inputColor1":CIColor(cgColor: UIColor.clear.cgColor)])
        // 获取带颜色的二维码
        guard let newOutPutImage = colorFilter?.outputImage else {
            return nil
        }
        
        // 缩放
        let scale = width / newOutPutImage.extent.width
        let transform = CGAffineTransform(scaleX: scale, y: scale)
        let output = newOutPutImage.transformed(by: transform)
        let qrCodeImage = UIImage(ciImage: output)
        
        guard let fillImage = iconImg else {
            return qrCodeImage
        }
        
        let imageSize = qrCodeImage.size
        UIGraphicsBeginImageContext(imageSize)
        qrCodeImage.draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
        let fillRect = CGRect(x: (width - width/5)/2, y: (width - width/5)/2, width: width/5, height: width/5)
        fillImage.draw(in: fillRect)
        
        guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return qrCodeImage }
        UIGraphicsEndImageContext()
        
        return newImage
    }
    
    /// 保存图片到相册
    ///
    /// - Parameters:
    ///   - image: 图片
    ///   - completion: 完成
    class func qs_saveImageToPhotoLibrary(_ image: UIImage, completion: @escaping ((Bool) -> ())) {
        // 判断授权状态
        let authStatus = PHPhotoLibrary.authorizationStatus()
        
        if authStatus == .denied || authStatus == .restricted {
            let alertView = QSAlertView.init(title: kGetString("警告"), content: kGetString("请先去设置中打开相册访问权限"), btnStr1: kGetString("取消"), btnTextColor1: kColor_666666, btnStr2: kGetString("去设置"), btnTextColor2: kColor_FF851A)
            alertView.showAlertView(action1: { (view) in
                view.hideAlertView()
            }) { (view) in
                let url = URL.init(string: UIApplication.openSettingsURLString)
                UIApplication.shared.openURL(url!)
                view.hideAlertView()
            }
            
            DispatchQueue.main.async {
                completion(false)
            }
        } else if (authStatus == .authorized) { // 用户允许当前应用访问相册
            PHPhotoLibrary.requestAuthorization { (status) in
                if status == .authorized {
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAsset(from: image)
                    }) { (success, error) in
                        DispatchQueue.main.async {
                            completion(success)
                        }
                    }
                }
            }
        } else if (authStatus == .notDetermined) { // 用户还没有做出选择
            PHPhotoLibrary.requestAuthorization { (status) in
                if status == .authorized {
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAsset(from: image)
                    }) { (success, error) in
                        DispatchQueue.main.async {
                            completion(success)
                        }
                    }
                } else {
                    DispatchQueue.main.async {
                        completion(false)
                    }
                }
            }
        }
    }
}
